import axios from "axios";
import { AxiosInstance, AxiosHeaders } from "axios";
import type {
  HRequestInterceptors,
  HRequestConfig,
} from "@/service/request/type";

const DEAUFT_LOADING = true;
const HEADER_REQUEST_DEFAULT = "multipart/form-data";

class HSequest {
  instance: AxiosInstance;
  interceptors?: HRequestInterceptors;
  loading?: any;

  constructor(config: HRequestConfig) {
    this.instance = axios.create(config);


    this.interceptors = config.interceptors;

    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    this.instance.interceptors.request.use(
      (config) => {
        return config;
      },
      (error) => {
        console.log("所有实例都有的拦截器请求失败");
        return error;
      }
    );

    this.instance.interceptors.response.use(
      (res) => {
        this.loading?.close();
        return res;
      },
      (error) => {
        console.log("所有实例都有的拦截器请求失败");
        this.loading?.close();
        if (error.response.status === 404) {
          console.log("404的错误");
        }
        return error;
      }
    );
  }

  request<T>(
    config: HRequestConfig<T>,
    header_content_type?: string
  ): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config);
      }

      //设置请求头的数据格式
      if (config.data) {
        config.headers = new AxiosHeaders().setContentType(header_content_type);
        if (!config.headers["Content-Type"]) {
          config.headers["Content-Type"] = HEADER_REQUEST_DEFAULT;
        }
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.requestInterceptor) {
            res = config.interceptors.responseInterceptor(res);
          }
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  get<T>(config: HRequestConfig<T>, header_content_type?: string): Promise<T> {
    return this.request<T>({ ...config, method: "GET" }, header_content_type);
  }

  post<T>(config: HRequestConfig<T>, header_content_type?: string): Promise<T> {
    return this.request<T>({ ...config, method: "POST" }, header_content_type);
  }

  delete<T>(
    config: HRequestConfig<T>,
    header_content_type?: string
  ): Promise<T> {
    return this.request<T>(
      { ...config, method: "DELETE" },
      header_content_type
    );
  }

  put<T>(config: HRequestConfig<T>, header_content_type?: string): Promise<T> {
    return this.request<T>({ ...config, method: "PUT" }, header_content_type);
  }
}

export default HSequest;
